<!DOCTYPE html>
<html lang="zh-cmn">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <meta name="renderer" content="webkit"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta name="format-detection" content="telephone=no"/>

    <title>microapp授权test</title>
    <script src="http://g.alicdn.com/dingding/open-develop/1.6.9/dingtalk.js"></script>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
      var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
          sURLVariables = sPageURL.split('&'),
          sParameterName,
          i;
        for (i = 0; i < sURLVariables.length; i++) {
          sParameterName = sURLVariables[i].split('=');
          if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
          }
        }
      };

      var corpId = getUrlParameter('corpId');
      var appId = getUrlParameter('appId');
      function conn(p_url, p_data, listener, p_type, format, timeout, showcontent) {
        if(timeout===undefined || timeout==null){
            timeout = 30000;
        }

        if(format===undefined || format===null){
            format = 'jsonp';
        }
        if(p_type === undefined || p_type==null){
            p_type = 'GET';
        }
        p_data["format"] = format;
        p_data["corp_id"] = corpId;
        p_data["app_id"] = appId;
        p_data["rand"] = new Date().getTime();
        $.ajax({
            type: p_type,
            url: p_url,
            data: p_data,
            dataType: format,
            timeout: timeout,
            context: $('body'),
            xhrFields: {
              withCredentials: true
            },
            success: function (data) {
                if (typeof listener.success === "function") {
                    listener.success(data);
                }
            },
            error: function (xhr, type) {
                if (typeof listener.error === "function") {
                    listener.error(xhr, type);
                }
            }
        })
    }
      function init_config() {
          $('#notify-btn').on('click', function () {
            dd.device.notification.alert({
              message: 'dd.device.notification.alert 内容',
              title: 'This is title 标题',
              buttonName: 'button按钮',
              onSuccess: function (data) {
                console.log('onSuccess: ', data);
              },
              onFail: function (err) {
                console.log('fail: ', err);
              }
            });
          });
          $('#user-btn').on('click', function () {
            dd.biz.user.get({
                onSuccess: function (info) {
                    $('#user-result').html(JSON.stringify(info))
                },
                onFail: function (err) {
                    $('#user-result').html(JSON.stringify(err))
                }
            });
          });
          $('#select-user-btn').on('click', function () {
            dd.biz.contact.complexPicker({
                title:"测试标题",            //标题
                corpId:corpId,              //企业的corpId
                multiple:true,            //是否多选
                limitTips:"超出了",          //超过限定人数返回提示
                maxUsers:1000,            //最大可选人数
                pickedUsers:[],            //已选用户
                pickedDepartments:[],          //已选部门
                disabledUsers:[],            //不可选用户
                disabledDepartments:[],        //不可选部门
                requiredUsers:[],            //必选用户（不可取消选中状态）
                requiredDepartments:[],        //必选部门（不可取消选中状态）
                appId:appId,              //微应用的Id
                permissionType:"GLOBAL",          //选人权限，目前只有GLOBAL这个参数
                responseUserOnly:false,        //返回人，或者返回人和部门
                startWithDepartmentId:0 ,   // 0表示从企业最上层开始
                onSuccess: function (info) {
                    $('#select-user-result').html(JSON.stringify(info))
                },
                onFail: function (err) {
                    $('#select-user-result').html(JSON.stringify(err))
                }
            });
          });
      }
      function auth_code_login(){
        dd.runtime.permission.requestAuthCode({
          corpId: corpId, //企业id
          onSuccess: function (info) {
            console.log('auth result', info);
            $('#auth-result').html('免登授权成功！获取用户信息...');
            conn('/api/dingtalk/isv/js/login', {"code": info.code}, {
                success: function (data) {
                  if(data.code !== 0){
                      $('#auth-result').html(data.message)
                  }else{
                      $('#auth-result').html(data.data.user.name+"<br>"+data.data.corp.corp_name)
                  }
                },
                error: function (xhr, type) {
                  $('#auth-result').html("网络错误")
                }
            });
          },
          onFail: function (err) {
            $('#auth-result').html('免登授权失败：' + JSON.stringify(err));
            console.log('requestAuthCode fail: ' + JSON.stringify(err));
          }
        });
      }
      function get_user_info(){
        conn('/api/dingtalk/isv/user/info', {}, {
            success: function (data) {
              if(data.code !== 0){
                  if(data.code === 10001){
                      auth_code_login();
                      return
                  }
                  $('#auth-result').html(data.message)
              }else{
                  $('#auth-result').html(data.data.user.name+"<br>"+data.data.corp.corp_name)
              }
            },
            error: function (xhr, type) {
              $('#auth-result').html("网络错误")
            }
        });
      }
      function dd_config(config){
        dd.config(config);
        dd.ready(function () {
          $('#conf-result').html('配置成功！');
          console.log('dd ready');
          document.addEventListener('pause', function () {
            console.log('pause');
          });
          document.addEventListener('resume', function () {
            console.log('resume');
          });
          init_config();
          get_user_info();

        });
        dd.error(function (err) {
          $('#conf-result').html('配置失败：' + JSON.stringify(err));
          console.log('dd error: ', err);
        });
      }
      function init(){
          conn('/api/dingtalk/isv/js/config', {}, {
            success: function (data) {
              console.log("result", data);
              if(data.code !== 0){
                  $('#url-p').html(data.message);
                  return
              }
              var config = data.data;
              config["jsApiList"] = ['device.notification.confirm',
                  'biz.contact.complexPicker',
                  'device.notification.alert',
                  'device.notification.prompt',
                  'biz.chat.chooseConversation',
                  'biz.ding.post',
                  'biz.user.get'
              ];
              dd_config(config);
            },
            error: function (xhr, type) {
              $('#auth-result').html("网络错误")
            }
        });
      }
      $(document).ready(function () {
          init();
      });
    </script>
</head>
<body>
<p id="url-p">
</p>
<p id="conf-result">
    配置中...
</p>
<p id="auth-result"></p>

<button id="notify-btn" class="btn btn-block btn-default">显示通知</button>
<button id="user-btn" class="btn btn-block btn-default">本地用户信息</button>
<p id="user-result"></p>
<button id="select-user-btn" class="btn btn-block btn-default">选择人员</button>
<p id="select-user-result"></p>

</body>
</html>